package middleware

import (
	"blog2021/model"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		if token := session.Get("token"); token != nil {
			if user, err := model.GetUserFromToken(token.(string)); err == nil {
				c.Set("user", user)
				c.Next()
				return
			}
		}
		c.Redirect(http.StatusTemporaryRedirect, "/login")
	}
}
